#region " LICENSE "
// DRILL - Dependency Resolution Interface Layer Library
// Copyright (c) 2008-2012 Wade A. Reynolds. All rights reserved.
// http://drill.codeplex.com/
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System.IO;
using System.Reflection;
using Drill.Core.Utilities;

namespace Drill.TestSupport
{
    public class TestDataDirectoryLocator
    {
        private const string TestDataDirectoryName = "TestData";
	    private const int MaxParentDirectoryTraversals = 6;

        public static string FindTestDataDirectory()
        {
            // Check to see if the test data directory exists:
            // 1. Start checking to see if it is a subdirectory 
			//    of the same directory in which the assembly resides.
            // 2. Traverse up one directory level and re-check iteratively 
			//    until the test data directory is found, until the 
			//    maximum number of directory traversals is reached or 
			//    until the current directory doe not exist.

			int attempt = 0;
            Assembly assembly = Assembly.GetExecutingAssembly();
			string currentDirectory = Path.GetDirectoryName(assembly.Location);

			while (attempt <= MaxParentDirectoryTraversals)
			{
				if (string.IsNullOrWhiteSpace(currentDirectory) || false == Directory.Exists(currentDirectory))
				{
					break;
				}

				string testDataDirectory = Path.Combine(currentDirectory, TestDataDirectoryName);
				if (Directory.Exists(testDataDirectory))
				{
					return testDataDirectory;
				}
				
				currentDirectory = PathUtility.GetParentPath(currentDirectory);
				
				attempt++;
			}

            return null;
        }
    }
}
